import { useSearchParams, useNavigate } from 'react-router-dom'
import { useRecoilValue } from 'recoil'
import { IYearList, IQuarterList } from '@/pages/DataFilling/type'
import { PublicEnum } from '@/@types'
import { userInfo } from '@/store/userInfo'

/**
 * @author LiuYu
 * @description 判断一个数组是否是空数组或者空对象
 * @param {any}
 * @return {Boolean}
 */
export const isNullArray = (item: any) => item && Object.keys(item).length > 0

/**
 * @author LiuYu
 * @description 判断接口返回是否有数据
 * @param {any}
 * @return {Boolean}
 */
export const isNullData = (item: any) => item && item.code === 200

/**
 * @author LiuYu
 * @description 判断接口返回是否有数据
 * @param {any}
 * @return {Boolean}
 */
export const isSuccess = (item: any) => item && item.success === 200

/**
 * @author LiuYu
 * @description 生成不重复字符串
 * @return {Number}
 */
export const getRandomString = () => {
  const length = 12 // 设置ID的长度
  const characters = '0123456789' // 可用字符集合
  let id = ''

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length)
    id += characters[randomIndex]
  }

  return +id
}

// 判断是否是字符串
export const isNumber = (name: any) => {
  if (Object.prototype.toString.call(name).slice(8, -1) === 'Number') {
    return true
  }
  return false
}

// 判断是否是数组
export const isArray = (name: any) => {
  if (Object.prototype.toString.call(name).slice(8, -1) === 'Array') {
    return true
  }
  return false
}

/**
 * @description 从url获取查询参数
 * @param {string} name
 */
export const getUrlParams = (name: string): any => {
  const [searchParams] = useSearchParams()
  return searchParams.get(name)
}

/**
 * @author LiuYu
 * @description 返回季度
 * @param {list} 原数据
 * @param {data} 当前选中的数据
 * @return {string}
 */
export const getTheQuarterName = (list: PublicEnum[], data: string[]) => {
  const year = list.find((item) => item.value === data[0])
  const label = year?.children?.find((item) => item.value === data[1])?.label
  return `${data[0]}${label}`
}

// 把后端的年份季度洗成Cascader组件可以接收的效果
export const washYear = (value: IYearList[]) =>
  value.map((item) => {
    const { dataReportYear, childrenList } = item
    const transformedChildrenList = childrenList.map((child) => {
      const { quarterId, quarterName } = child
      return {
        value: quarterId,
        label: quarterName,
      }
    })
    return {
      label: dataReportYear,
      value: dataReportYear,
      children: transformedChildrenList,
    }
  })

/**
 * excel文件下载
 * @param data：流文件，格式Blob
 * @param name：字符串
 * @param type: 后缀
 */
export const exportData = (data: any, name: string, type: string) => {
  // 设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
  const url = window.URL.createObjectURL(data)
  // 创建A标签
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  // 触发点击方法
  link.setAttribute('download', `${name}.${type}`)

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

// /**
//  * 走查看
//  * @param data：流文件，格式Blob
//  * @param name：字符串
//  */
// export const viewResource = (data: any, name: string) => {
//   const url = window.URL.createObjectURL(data)
//   window.open(url, '_blank')
// }

// 转换三级联动数据结构函数封装
// data : 返回的整个三级联动数据
export const convertDataToCascaderFormat = (data: any) =>
  data.map((item: any) => ({
    value: item.id,
    label: item.name,
    children: item.children.length ? convertDataToCascaderFormat(item.children) : [],
  }))
/**
 * @author LiuYu
 * @description 判断角色
 * @param {number} role 角色
 * @return {boolean} true | false
 */
export const havePpermission = (role: number[] | number) => {
  const { accountType } = useRecoilValue(userInfo)
  if (isNumber(role)) {
    return role === accountType
  }

  if (role instanceof Array && isArray(role)) {
    return role.includes(accountType)
  }

  return false
}

// md 将三级联动数字转换成文字
export const findLabelByValue = (data: any, value: any) => {
  for (let i = 0; i < data?.length; i++) {
    if (data[i].value === value) {
      return data[i].label
    }
    if (data[i].children && data[i].children.length > 0) {
      const label: any = findLabelByValue(data[i].children, value)
      if (label) {
        return label
      }
    }
  }
  return null
}

// 重构三级联动数据结构
export const convertToAntdData = (data: any) => {
  const antdData: any = []
  function convertChildren(children: any) {
    if (!children || children.length === 0) {
      return []
    }
    return children.map((child: any) => ({
      value: child.id,
      label: child.name,
      children: convertChildren(child.children),
    }))
  }
  data.forEach((item: any) => {
    const antdItem = {
      value: item.id,
      label: item.name,
      children: convertChildren(item.children),
    }
    antdData.push(antdItem)
  })
  return antdData
}

// todo 找出地区 id 对应的省名字
// threeLevelArray 级联结构  value label
// 用数组[11,234,555]去查
export const findNamesByIds = (threeLevelArray: any, idsArray: any) => {
  const result = []
  for (const firstLevelItem of threeLevelArray) {
    if (idsArray.includes(firstLevelItem.value)) {
      result.push(firstLevelItem.label)
    }
    // console.log('xxxxxxxxxxxxxxxxxxxxxxxxx🦢🦢', result)
    for (const secondLevelItem of firstLevelItem.children) {
      if (idsArray.includes(secondLevelItem.value)) {
        result.push(secondLevelItem.label)
      }
      for (const thirdLevelItem of secondLevelItem.children) {
        if (idsArray.includes(thirdLevelItem.value)) {
          result.push(thirdLevelItem.label)
        }
      }
    }
  }
  return result
}
